<template>
<el-container>
  <el-main>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="二维码名称" prop="qrcodeName">
            <el-input v-model="form.qrcodeName" placeholder="请输入二维码名称" />
          </el-form-item>
          <el-form-item label="添加验证" prop="isVerified">
            <el-switch v-model="form.isVerified" :active-value="1" :inactive-value="2"></el-switch>
          </el-form-item>
          <el-form-item label="使用成员" prop="employees">
            <EmployeeSelect :default-employees="employeeList" placeholder="请选择使用成员" @selectedEmployees="empSelected"></EmployeeSelect>
          </el-form-item>
          <el-form-item label="入群打标签">
            <el-cascader
              :options="options"
              :props="props"
              v-model="tagList"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="入群引导语" prop="leadingWords">
            <el-input v-model="form.leadingWords" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
        <el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="22">
          <el-form-item label="添加群聊">
            <GroupchatSelect @selected="groupchatAdd"></GroupchatSelect>
            <el-table :data="groupchatList">
              <el-table-column label="群名称(人数)" align="center" prop="name" >
                <template slot-scope="scope">
                  {{scope.row.name}}<br/>
                  ({{scope.row.memberNum}}/{{scope.row.max}})
                </template>
              </el-table-column>
              <el-table-column label="群主/管理员" align="center" prop="owner.name" ></el-table-column>
              <el-table-column label="群成员上限" align="center" prop="qrcodeName" >
                <template slot-scope="scope">
                  群人数达到<el-input-number size="mini" v-model="scope.row.max" :step="10" :max="500" :min="scope.row.memberNum"></el-input-number>人,换群加入
                </template>
              </el-table-column>
              <el-table-column label="群二维码" align="center" prop="qrcodeName" >
                <template slot-scope="scope">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadFileUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :limit="1"
                    :on-error="handleUploadError"
                    :on-exceed="handleExceed"
                    :on-success="function (res,file){return handleUploadSuccess(res,file,scope.row)}"
                    :before-upload="beforeQrcodeUpload">
                    <el-image v-if="scope.row.qrcodeUrl" :src="scope.row.qrcodeUrl" fit="fill" class="avatar"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" prop="qrcodeName" >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleRemoveRow(scope.row)"
                    v-hasPermi="['wework:groupchatAutoPull:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-main>
  <el-footer>
    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="cancel">取 消</el-button>
  </el-footer>
</el-container>
</template>
<script>
import {addGroupchatAutoPull, getGroupchatAutoPull, updateGroupchatAutoPull} from "@/api/wework/groupchatAutoPull";
import GroupchatSelect from "@/components/GroupchatSelect";
import EmployeeSelect  from "@/components/EmployeeSelect"
import {listTag} from "@/api/wework/tag"
import Template from "@/views/multitenant/template";
import {getToken} from "@/utils/auth";
export default {
  name:"GroupchatAutoPullEdit",
  components: {Template, GroupchatSelect,EmployeeSelect},
  data() {
    return {
      props: { multiple: true },
      // options:[{value:1,label:'东南',children:[{value:3,label:'上海'},{value:4,label:'南京'},{value:5,label:'杭州'}]},
      //   {value:6,label:'西北',children:[{value:7,label:'西安'},{value:8,label:'兰州'},{value:9,label:'银川'}]}],
      options:[],
      //按钮loading
      buttonLoading: false,
      autoPullId:null,
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      //使用成员
      employeeList:[],
      //添加群聊
      groupchatList:[],
      //标签
      tagList:[],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qrcodeName: [
          { required: true, message: "二维码名称不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    //修改时通过url获取id
    this.autoPullId = this.$route.params && this.$route.params.autoPullId;
    this.employeeList = [];
    this.groupchatList = [];
    if (this.autoPullId){
      this.getInfo(this.autoPullId);
      this.form.id = this.autoPullId;
    }
  },
  mounted() {
    this.getTagList();
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getTagList(){
      listTag().then(response => {
        this.tagGroups = response.data;
        this.options = this.tagGroups.map(g=>{
          let group = {};
          group.value = g.id;
          group.label = g.groupName;
          group.children=g.tagList.map(t=>{return {value:t.id,label:t.name}});
          return group;
        });
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        corpId: undefined,
        qrcodeName: undefined,
        qrcodeUrl: undefined,
        wxConfigId: undefined,
        isVerified: undefined,
        leadingWords: undefined,
        employees: undefined,
        groupchats: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    empSelected(data){
      console.log("=====");
      console.log(data);
      this.employeeList = data;
    },
    groupchatAdd(groupchatList){
      this.groupchatList = this.groupchatList.concat(groupchatList);
    },
    beforeQrcodeUpload(file) {
      const allowedType = ['image/jpeg','image/png'];
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isAllowedType = allowedType.indexOf(file.type)!=-1;
      if (!isAllowedType) {
        this.$message.error('上传二维码图片只能是 JPG或PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传二维码图片大小不能超过 2MB!');
      }
      return isAllowedType && isLt2M;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file,row) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.$message.success("上传成功");
      this.$emit("input", res.data.url);
      //需要通过这种方式set进去,否则不发生变化，监听不到,参考 https://cn.vuejs.org/v2/guide/reactivity.html#%E5%AF%B9%E4%BA%8E%E5%AF%B9%E8%B1%A1
      this.$set(row,'qrcodeUrl',res.data.url);
    },
    handleRemoveRow(row){
      console.log(row)
      let index = this.groupchatList.findIndex(g=>g.id===row.id);
      this.groupchatList.splice(index,1);
    },
    /** 修改按钮操作 */
    getInfo(autoPullId) {
      this.loading = true;
      this.reset();
      getGroupchatAutoPull(autoPullId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.groupchatList = JSON.parse(this.form.groupchats);
        this.employeeList = JSON.parse(this.form.employees);
        this.tagList = JSON.parse(this.form.tags);
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.employees = JSON.stringify(this.employeeList);
          this.form.groupchats = JSON.stringify(this.groupchatList.map(g=>{return {id:g.id,max:g.max,qrcodeUrl:g.qrcodeUrl}}));
          this.form.tags = JSON.stringify(this.tagList);
          // const employees = this.form.employees.map(item => item.id);
          // this.form.employees = employees.join(",");
          if (this.form.id != null) {
            updateGroupchatAutoPull(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGroupchatAutoPull(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          //关闭当前页签，跳转到自动拉群列表页签
          this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
          let GroupchatAutoPullTabIndex = this.$store.state.tagsView.visitedViews.findIndex(v=>{return v.name==='GroupchatAutoPull'})
          this.$router.push(this.$store.state.tagsView.visitedViews[GroupchatAutoPullTabIndex].path)
        }
      });
    },
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.hide .el-upload{
  display: none;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
